<?php
if (!defined('ABSPATH')) {
    exit;
}

class NX_Custom_Sort_Ajax {
    public function __construct() {
        add_action('wp_ajax_nx_custom_sort_save_rule', [$this, 'save_rule']);
        add_action('wp_ajax_nx_custom_sort_create_page', [$this, 'create_page']);
        add_action('wp_ajax_nx_custom_sort_get_items', [$this, 'get_items']);
        add_action('wp_ajax_nopriv_nx_custom_sort_log_visit', [$this, 'log_visit']);
        add_action('wp_ajax_nx_custom_sort_log_visit', [$this, 'log_visit']);
    }

    public function save_rule() {
        check_ajax_referer('nx-custom-sort-nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }

        $rule_name = sanitize_text_field($_POST['rule_name']);
        $post_type = sanitize_text_field($_POST['post_type']);
        $category_slug = sanitize_text_field($_POST['category_slug']);
        $slugs = array_map('sanitize_text_field', explode(',', $_POST['slugs']));
        $sort_order = array_map('intval', $_POST['sort_order']);

        $result = NX_Custom_Sort_DB::save_rule($rule_name, $post_type, $category_slug, $slugs, $sort_order);
        if ($result) {
            wp_send_json_success('Rule saved');
        } else {
            wp_send_json_error('Failed to save rule');
        }
    }

    public function create_page() {
        check_ajax_referer('nx-custom-sort-nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }

        $rule_id = intval($_POST['rule_id']);
        $rule = NX_Custom_Sort_DB::get_rule($rule_id);
        if (!$rule) {
            wp_send_json_error('Invalid rule ID');
        }

        $page_id = wp_insert_post([
            'post_title' => $rule->rule_name . ' Sorted List',
            'post_content' => '[nx_custom_sort_list rule_id="' . $rule_id . '"]',
            'post_status' => 'publish',
            'post_type' => 'page'
        ]);

        if ($page_id) {
            update_post_meta($page_id, '_nx_custom_sort_rule_id', $rule_id);
            wp_send_json_success(['page_id' => $page_id]);
        } else {
            wp_send_json_error('Failed to create page');
        }
    }

    public function get_items() {
        check_ajax_referer('nx-custom-sort-nonce', 'nonce');
        $post_type = sanitize_text_field($_POST['post_type']);
        $category_slug = sanitize_text_field($_POST['category_slug']);
        $slugs = array_map('sanitize_text_field', $_POST['slugs']);
        $args = [
            'post_type' => $post_type,
            'posts_per_page' => -1
        ];
        if ($category_slug) {
            $args['tax_query'] = [
                [
                    'taxonomy' => $post_type === 'product' ? 'product_cat' : 'category',
                    'field' => 'slug',
                    'terms' => $category_slug
                ]
            ];
        }
        if ($slugs) {
            $args['post_name__in'] = $slugs;
        }
        $query = new WP_Query($args);
        $items = [];
        while ($query->have_posts()) {
            $query->the_post();
            $items[] = ['id' => get_the_ID(), 'title' => get_the_title()];
        }
        wp_reset_postdata();
        wp_send_json_success($items);
    }

    public function log_visit() {
        check_ajax_referer('nx-custom-sort-nonce', 'nonce');
        $page_id = intval($_POST['page_id']);
        NX_Custom_Sort_DB::log_visit($page_id);
        wp_send_json_success();
    }
}

?>
